'''
作业三：参照本周视频 字符编码 最后的项目补全代码：
1. 实现图片转字符画类I2Char中genCharImage方法pass占位的代码，该方法将图片转化成字符画
2. 在main函数中 ，实现通过命令行调用图片转字符画功能pass占位的代码 ,命令行执行 Python v2char.py t3.jpeg,输出字符画
'''
import sys
import os
import cv2

# 基类
class CharFrame:
    ascii_char = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
    def pixelToChar(self, luminance):
        return self.ascii_char[int(luminance / 256 * len(self.ascii_char))]

    def convert(self, img, limitSize=-1, fill=False, wrap=False):
        if limitSize != -1 and (img.shape[0] > limitSize[1] or img.shape[1] > limitSize[0]):
            img = cv2.resize(img, limitSize, interpolation=cv2.INTER_AREA)
        print(img,'——————————————————')
        ascii_frame = ''
        blank = ''
        if fill:
            blank += ' ' * (limitSize[0] - img.shape[1])
        if wrap:
            blank += '\n'
        for i in range(img.shape[0]):
            for j in range(img.shape[1]):
                ascii_frame += self.pixelToChar(img[i, j])
            ascii_frame += blank
        return ascii_frame
    # 这里的img应该是一个数组，数组才有shape() 方法，str是没有的，所以要转变为数组的模式
class I2Char(CharFrame):
    result = None
    def __init__(self, path, limitSize = -1, fill = False, wrap = False):
        self.genCharImage(path, limitSize, fill, wrap)
    def genCharImage(self, path, limitSize = -1, fill = False, wrap = False):
        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        frame = self.convert(img, os.get_terminal_size(),fill = True)
        self.result = frame

    def show(self, stream=2):
        if self.result is None:
            return
        if stream == 1 and os.isatty(sys.stdout.fileno()):
            self.streamOut = sys.stdout.write
            self.streamFlush = sys.stdout.flush
        elif stream == 2 and os.isatty(sys.stderr.fileno()):
            self.streamOut = sys.stderr.write
            self.streamFlush = sys.stderr.flush
        elif hasattr(stream, 'write'):
            self.streamOut = stream.write
            self.streamFlush = stream.flush
        self.streamOut(self.result)
        self.streamFlush()
        self.streamOut('\n')

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('file',help='Image file, .jepg or .png')
    args = parser.parse_args()
    i2char = I2Char(args.file)
    i2char.show()
